package net.quanter.shield.common.dto.result.page;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Getter;
import lombok.ToString;
import net.quanter.shield.common.dto.result.ResultDTO;
import net.quanter.shield.common.enums.http.HttpCode;

/**
 * @author 王老实
 * @since 1.3.12.RELEASE
 */
@ToString
public class ListPageResultDTO<T extends Serializable> extends ResultDTO<List<T>> {

    @Getter
    @Schema(description = "分页对象")
    private PageInfoDTO page;
    private final List<T> emptyList = List.of();

    public ListPageResultDTO() {
        super(true, null, null, null);
    }

    public ListPageResultDTO(boolean success, String message, Integer code) {
        super(true, message, code, null);
    }

    public ListPageResultDTO(List<T> data, PageInfoDTO pageInfoDTO) {
        super(true, null, HttpCode.SUCCESS.code, data);
        this.page = pageInfoDTO;
    }

    public <N extends Serializable> ListPageResultDTO<N> convert(Function<T, N> action) {
        ListPageResultDTO<N> newListPageResultDTO = new ListPageResultDTO<>(this.isSuccess(), this.getMessage(), this.getCode());
        newListPageResultDTO.page = this.page;
        List<N> dataList = this.get()
                .map(x -> x.stream().map(action).collect(Collectors.toList()))
                .orElse(new ArrayList<>());
        newListPageResultDTO.data(dataList);
        return newListPageResultDTO;
    }
}
